<template>
  <div class="scanner">
    <van-nav-bar title="按件上架" left-text="返回" @click-left="onClickLeft"></van-nav-bar>
    <van-row style="margin-top: 0.5rem;" type="flex" justify="center">
      <van-col>
        <van-form>
          <!-- <van-field label="货主" v-model="storerName"  disabled/>
                    <van-field label="仓库" v-model="wareHouseName" disabled/>
                    <van-field label="品牌" v-model="brandName" disabled/> -->
          <van-field label="仓位" v-model="locationTypeName" disabled />
          <van-field
            v-model="putawayParams.recCartonNumber"
            ref="recCartonNumber"
            id="recCartonNumber"
            name="箱号"
            label="箱号"
            placeholder="箱号"
            @focus="recCartonNumberFocusClick"
            @click="recCartonNumberFocusClick"
            :readonly="recCartonNumberReadOnly"
            @keyup.enter.native="verifyRecCartonNumber"
          />
          <van-field
            v-model="putawayParams.barCode"
            ref="barCode"
            id="barCode"
            name="SKU"
            label="SKU"
            placeholder="SKU"
            @focus="barCodeFocusClick"
            @click="barCodeFocusClick"
            :readonly="barCodeReadOnly"
            @keyup.enter.native="verifySku"
          />
          <van-field
            v-model="putawayParams.locationCode"
            ref="locationCode"
            id="locationCode"
            name="库位"
            label="库位"
            placeholder="库位"
            @focus="locationCodeFocusClick"
            @click="locationCodeFocusClick"
            :readonly="locationCodeReadOnly"
            @keyup.enter.native="verifyLocation"
          />
          <van-row style="margin-left:16px">
            <van-col span="12">
              <van-cell title="数量" class="van-cell-style">
                <input
                  v-model="putawayParams.putawayQty"
                  ref="putawayQty"
                  id="putawayQty"
                  onkeyup="value=value.replace(/[^\d]/g,'')"
                  class="van-field__control"
                  readonly
                />
              </van-cell>
            </van-col>
            <van-col span="12">
              <van-cell title="负数" class="van-cell-style">
                <template #right-icon>
                  <van-checkbox shape="square" v-model="minusChecked" @click="minusClick()" style="width:50%" />
                </template>
              </van-cell>
            </van-col>
          </van-row>
          <van-row style="margin-top:16px;margin-left:16px">
            <van-col span="8">
              <van-cell
                title="可上架"
                class="van-cell-style"
                v-model="putawayParams.allowPutawayQty"
                ref="allowPutawayQty"
                id="allowPutawayQty"
              />
            </van-col>
            <van-col span="8" style="text-align:center">
              <van-cell
                title="已上架"
                class="van-cell-style"
                v-model="putawayParams.oldPutawayQty"
                ref="oldPutawayQty"
                id="oldPutawayQty"
              />
            </van-col>
            <van-col span="8" style="text-align:center">
              <van-cell title="差异" class="van-cell-style" v-model="putawayParams.differQty" ref="differQty" id="differQty" />
            </van-col>
          </van-row>
        </van-form>
        <div style="float: right; margin: 8px;">
          <van-button type="primary" size="small" @click="clickNextCarton()">下一箱</van-button>
        </div>
      </van-col>
    </van-row>
    <!-- 普通消息响应遮罩层 -->
    <van-overlay :show="showMsgOverlay">
      <div class="wrapper">
        <div>
          <van-row>
            <div class="msgTxt">{{ showMsg }}</div>
          </van-row>
          <van-row style="margin-top:64px">
            <van-col span="24" style="text-align:center">
              <van-button type="primary" @click="closeOverlay()">关闭</van-button>
            </van-col>
          </van-row>
        </div>
      </div>
    </van-overlay>
    <!-- 复杂消息响应遮罩层 -->
    <van-overlay :show="showComplexMsgOverlay">
      <div class="wrapper">
        <div>
          <van-row>
            <div class="msgTxt">{{ showComplexMsg }}</div>
          </van-row>
          <van-row style="margin-top:64px">
            <van-col span="12" style="text-align:center">
              <van-button type="primary" @click="closeComplexOverlay()">取消</van-button>
            </van-col>
            <van-col span="12" style="text-align:center">
              <van-button type="primary" @click="nextCarton()">继续</van-button>
            </van-col>
          </van-row>
        </div>
      </div>
    </van-overlay>

    <!-- 加载遮罩 -->
    <van-overlay :show="showLoadingOverlay">
      <div class="wrapper">
        <div>
          <van-row>
            <div class="msgTxt">加载中......</div>
          </van-row>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
import {mapGetters} from "vuex";
import {verifyRecCartonNumber, verifyLocation, verifySku, excuteItemPutaway} from "@/api/biz/putaway/boxPutaway.js";
export default {
  name: "itemPutaway",
  computed: {
    ...mapGetters("user", ["userData"]),
    ...mapGetters("scanner", ["pdaScanData"])
  },
  watch: {
    // 扫描枪操作
    pdaScanData: {
      handler(data) {
        this.scanEvent(data.data);
        let input = document.activeElement.id;
        if (input == "recCartonNumber") {
          this.putawayParams.recCartonNumber = data.data;
          this.verifyRecCartonNumber();
        }
        if (input == "barCode") {
          this.putawayParams.barCode = data.data;
          this.verifySku();
        }
        if (input == "locationCode") {
          this.putawayParams.locationCode = data.data;
          this.verifyLocation();
        }
      },
      deep: true
    }
  },
  created() {
    // 默认光标在箱号框
    this.recCartonNumberFocus();
    this.putawayParams.user = this.userData.sysUserLoginName;
    // 获取货主/仓库/品牌
    if (this.$root.storerWarehouseBrand === undefined) {
      this.msgShowTime("请重新登录，并设置货主、仓库、品牌");
    } else {
      this.putawayParams.storerId = this.$root.storerWarehouseBrand.storerId;
      this.putawayParams.wareHouseId = this.$root.storerWarehouseBrand.warehouseId;
      this.putawayParams.brandId = this.$root.storerWarehouseBrand.brandId;
    }
  },
  data() {
    return {
      // 只读选项
      recCartonNumberReadOnly: false,
      locationCodeReadOnly: false,
      barCodeReadOnly: false,
      // 定义扫描数据
      scanData: [],

      // 库位属性
      locationTypeName: "",

      // 表单参数
      putawayParams: {
        businessType: "B2B",
        storerId: "",
        wareHouseId: "",
        brandId: "",
        putawayQty: "1",
        recCartonNumber: "",
        barCode: "",
        locationId: "",
        locationCode: "",
        allowPutawayQty: 0,
        oldPutawayQty: 0,
        differQty: 0
      },
      // 负数选择框
      minusChecked: false,
      // 消息遮罩层参数
      showMsgOverlay: false,
      showMsg: "",
      showComplexMsgOverlay: false,
      showComplexMsg: "",
      // 当前得失焦点的文本框
      currentBlurName: "",

      // 加载遮罩
      showLoadingOverlay: false
    };
  },
  methods: {
    // 扫描枪扫描
    clickEvent() {
      this.scanData = [];
      // this.$toast.success("扫描数据被清理了");
    },
    scanEvent(data) {
      this.scanData.push(data);
    },
    scanErrorEvent() {},
    cellClickEvent() {},

    // 箱号框点击或失焦
    recCartonNumberFocusClick() {
      this.recCartonNumberReadOnly = true;
      // 记录当前对象
      this.currentBlurName = "recCartonNumber";
      setTimeout(() => {
        this.recCartonNumberReadOnly = false;
      }, 200);
    },
    // SKU框点击或者失焦
    barCodeFocusClick() {
      this.barCodeReadOnly = true;
      // 记录当前对象
      this.currentBlurName = "barCode";
      setTimeout(() => {
        this.barCodeReadOnly = false;
      }, 200);
    },
    // 库位框点击或失焦
    locationCodeFocusClick() {
      this.locationCodeReadOnly = true;
      // 记录当前对象
      this.currentBlurName = "locationCode";
      setTimeout(() => {
        this.locationCodeReadOnly = false;
      }, 200);
    },
    // 焦点聚焦到箱号框
    recCartonNumberFocus() {
      this.$nextTick(() => {
        this.$refs.recCartonNumber.focus();
      });
    },
    // 选中负数文本框
    minusClick() {
      let ref = this.currentBlurName;
      this.putawayParams.putawayQty =
        this.minusChecked == true ? -Math.abs(this.putawayParams.putawayQty) : Math.abs(this.putawayParams.putawayQty);
      if (ref == "recCartonNumber") {
        this.putawayParams.recCartonNumber = "";
        this.recCartonNumberFocus();
      }
      if (ref == "barCode") {
        this.putawayParams.barCode = "";
        this.skuFocus();
      }
      if (ref == "locationCode") {
        this.putawayParams.locationCode = "";
        this.putawayParams.locationId = "";
        this.locationFocus();
      }
    },
    // 验证箱号是否存在
    verifyRecCartonNumber() {
      // 验证货主/仓库/品牌
      if (this.$root.storerWarehouseBrand === undefined) {
        this.msgShowTime("请重新登录，并设置货主、仓库、品牌");
        return false;
      }
      if (this.putawayParams.recCartonNumber == "") {
        this.msgShowTime("请输入箱号！");
        // 定位到箱号
        this.recCartonNumberFocus();
        return false;
      }
      // 加载遮罩
      this.showLoadingOverlay = true;
      verifyRecCartonNumber(this.putawayParams).then(response => {
        // 加载遮罩
        this.showLoadingOverlay = false;
        if (response.data.status) {
          let storerId = response.data.data.storerId;
          let wareHouseId = response.data.data.wareHouseId;
          let brandId = response.data.data.brandId;
          if (
            this.putawayParams.storerId == storerId &&
            this.putawayParams.wareHouseId == wareHouseId &&
            this.putawayParams.brandId == brandId
          ) {
            // 赋值
            this.putawayParams.storerId = storerId;
            this.putawayParams.wareHouseId = wareHouseId;
            this.putawayParams.brandId = brandId;
            this.putawayParams.allowPutawayQty = response.data.data.allowPutawayQty;
            this.putawayParams.differQty = response.data.data.differQty;
            this.putawayParams.oldPutawayQty = response.data.data.oldPutawayQty;

            this.locationTypeName = response.data.data.locationTypeName;
            // 箱号验证成功后光标跳转至SKU
            this.skuFocus();
          } else {
            // 当前登录账号没有该箱的操作权限，清掉箱号/库位
            this.resetPageParams();
            this.recCartonNumberFocus();
            this.msgShowTime("当前登录账号没有该箱的操作权限！");
          }
        } else {
          this.resetPageParams();
          this.clearBaseInformation();
          this.msgShowTime(response.data.message);
        }
      });
    },
    // 清除页面数据
    resetPageParams() {
      this.putawayParams.recCartonNumber = "";
      this.putawayParams.barCode = "";
      this.putawayParams.locationCode = "";
      this.putawayParams.locationId = "";
      this.putawayParams.allowPutawayQty = 0;
      this.putawayParams.differQty = 0;
      this.putawayParams.oldPutawayQty = 0;
      this.putawayParams.putawayQty = 1;
      this.minusChecked = false;
    },
    // 清除货主仓库品牌数据
    clearBaseInformation() {
      this.locationTypeName = "";
    },
    // 光标跳转至SKU
    skuFocus() {
      this.$nextTick(() => {
        this.$refs.barCode.focus();
      });
    },
    // 验证SKU是否有效
    verifySku() {
      // 验证货主/仓库/品牌
      if (this.$root.storerWarehouseBrand === undefined) {
        this.msgShowTime("请重新登录，并设置货主、仓库、品牌");
        return false;
      }
      let recCartonNumber = this.putawayParams.recCartonNumber;
      let barCode = this.putawayParams.barCode;
      if (recCartonNumber == "") {
        this.msgShowTime("请先填写箱号！");
        this.resetPageParams();
        this.clearBaseInformation();
        this.recCartonNumberFocus();
        return false;
      }
      if (barCode == "") {
        this.msgShowTime("SKU不能为空！");
        // 焦点重新聚焦到SKU
        this.skuFocus();
        return false;
      }
      // 加载遮罩
      this.showLoadingOverlay = true;
      verifySku(this.putawayParams).then(response => {
        // 加载遮罩
        this.showLoadingOverlay = false;
        if (response.data.status) {
          // 箱号验证成功后光标跳转至SKU
          this.locationFocus();
        } else {
          this.putawayParams.barCode = "";
          this.skuFocus();
          this.msgShowTime(response.data.message);
        }
      });
    },
    // 光标跳转至库位
    locationFocus() {
      this.$nextTick(() => {
        this.$refs.locationCode.focus();
      });
    },
    // 验证库位是否存在
    verifyLocation() {
      // 验证货主/仓库/品牌
      if (this.$root.storerWarehouseBrand === undefined) {
        this.msgShowTime("请重新登录，并设置货主、仓库、品牌");
        return false;
      }
      let recCartonNumber = this.putawayParams.recCartonNumber;
      let locationCode = this.putawayParams.locationCode;
      let barCode = this.putawayParams.barCode;
      if (recCartonNumber == "") {
        this.msgShowTime("请先填写箱号！");
        this.recCartonNumberFocus();
        this.resetPageParams();
        return false;
      }
      if (barCode == "") {
        this.msgShowTime("请先填写SKU！");
        this.putawayParams.locationCode = "";
        this.putawayParams.locationId = "";
        this.skuFocus();
        return false;
      }
      if (locationCode == "") {
        this.msgShowTime("库位不能为空！");
        this.locationFocus();
        return false;
      }
      // 加载遮罩
      this.showLoadingOverlay = true;
      verifyLocation(this.putawayParams).then(response => {
        // 加载遮罩
        this.showLoadingOverlay = false;
        if (response.data.status) {
          // 验证成功，赋值库位ID
          this.putawayParams.locationId = response.data.data;
          // 直接执行上架操作
          this.excuteItemPutaway();
        } else {
          this.putawayParams.locationId = "";
          this.putawayParams.locationCode = "";
          this.msgShowTime(response.data.message);
          this.locationFocus();
        }
      });
    },
    // 确认上架
    excuteItemPutaway() {
      // 验证货主/仓库/品牌
      if (this.$root.storerWarehouseBrand === undefined) {
        this.msgShowTime("请重新登录，并设置货主、仓库、品牌");
        return false;
      }
      if (this.putawayParams.recCartonNumber == "") {
        this.msgShowTime("箱号不能为空！");
        this.resetPageParams();
        this.clearBaseInformation();
        this.recCartonNumberFocus();
        return false;
      }
      if (this.putawayParams.barCode == "") {
        this.msgShowTime("SKU不能为空！");
        this.putawayParams.locationCode = "";
        this.putawayParams.locationId = "";
        this.skuFocus();
        return false;
      }
      if (this.putawayParams.locationCode == "") {
        this.msgShowTime("库位不能为空！");
        this.locationFocus();
        return false;
      }
      if (Number(this.putawayParams.differQty) == 0 && this.minusChecked == false) {
        // && this.minusChecked == false
        // 只要差异为0了，就只可以进行负数操作
        this.msgShowTime("差异数量为0，不可上架！");
        this.resetPageParams();
        this.clearBaseInformation();
        this.recCartonNumberFocus();
        return false;
      }
      if (this.minusChecked == false && Math.abs(Number(this.putawayParams.differQty)) < Number(this.putawayParams.putawayQty)) {
        this.msgShowTime("上架数量大于差异数量，不可上架！");
        this.locationFocus();
        return false;
      }
      if (this.minusChecked) {
        if (Math.abs(this.putawayParams.putawayQty) > this.putawayParams.oldPutawayQty) {
          this.msgShowTime("下架数量大于已上架数量，不可下架！");
          this.locationFocus();
          return false;
        }
      }
      // 加载遮罩
      this.showLoadingOverlay = true;
      excuteItemPutaway(this.putawayParams).then(response => {
        // 加载遮罩
        this.showLoadingOverlay = false;
        if (response.data.status) {
          // 箱号(与其查询的信息)不清，光标置于SKU处
          // this.putawayParams.recCartonNumber = "";
          this.putawayParams.barCode = "";
          this.skuFocus();
          this.putawayParams.locationCode = "";
          this.putawayParams.locationId = "";
          // 可上架数量不变
          // 已上架数量
          this.putawayParams.oldPutawayQty = Number(this.putawayParams.oldPutawayQty) + Number(this.putawayParams.putawayQty);
          this.putawayParams.differQty = Number(this.putawayParams.differQty) + Number(this.putawayParams.putawayQty);
          this.minusChecked = false;
          this.putawayParams.putawayQty = 1;
          this.$notify({type: "success", message: response.data.message});
        } else {
          this.msgShowTime(response.data.message);
          // 箱号相关的数据不清，光标移到SKU，让用户从SKU继续操作
          // this.putawayParams.recCartonNumber = "";
          this.putawayParams.barCode = "";
          this.skuFocus();
          this.putawayParams.locationCode = "";
          this.putawayParams.locationId = "";
          this.minusChecked = false;
          this.putawayParams.putawayQty = 1;
        }
      });
    },
    // 返回上一级页面
    onClickLeft() {
      this.$router.push({
        name: "b2bPutaway"
      });
    },
    // 遮罩层消息展示设置
    msgShowTime(msg) {
      this.showMsg = msg;
      this.showMsgOverlay = true;
      // setTimeout(() => {
      //     this.showMsgOverlay = false;
      // }, 3000);
    },
    // 点击下一箱
    clickNextCarton() {
      // 当前箱还有未上架的商品，提醒是否继续开始下一箱
      if (this.recCartonNumber != "" && Number(this.putawayParams.differQty) != 0) {
        this.showComplexMsg = "该箱还未上架完成，是否继续？";
        this.showComplexMsgOverlay = true;
      } else {
        this.$notify({type: "success", message: "开始下一箱！"});
        this.nextCarton();
      }
    },
    // 开始下一箱，清空内容
    nextCarton() {
      // 关闭遮罩层
      this.showComplexMsgOverlay = false;
      // 重置查询条件，默认选中箱号
      // 默认焦点聚焦到箱号框
      this.recCartonNumberFocus();
      // 获取当前登录用户名
      this.putawayParams.user = this.userData.sysUserLoginName;
      this.resetPageParams();
      this.clearBaseInformation();
    },
    // 关闭遮罩
    closeOverlay() {
      this.showMsgOverlay = false;
      // 将焦点回到原位置
      if (this.currentBlurName == "recCartonNumber") {
        this.recCartonNumberFocus();
      } else if (this.currentBlurName == "barCode") {
        this.skuFocus();
      } else {
        this.locationFocus();
      }
    },
    // 关闭遮罩
    closeComplexOverlay() {
      this.showComplexMsgOverlay = false;
      // 将焦点回到原位置
      if (this.currentBlurName == "recCartonNumber") {
        this.recCartonNumberFocus();
      } else if (this.currentBlurName == "barCode") {
        this.skuFocus();
      } else {
        this.locationFocus();
      }
    }
  }
};
</script>

<style lang="less">
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.msgTxt {
  margin: 8px 83px 0;
  font-size: 18px;
  color: white;
}

.van-cell-style {
  .van-cell__value {
    width: 40%;
    text-align: center;
    color: red;
  }
  padding-right: 0px;
  padding-left: 0px;
}

.van-field__control {
  display: block;
  box-sizing: border-box;
  width: 100%;
  min-width: 0;
  margin: 0 0 0 16px;
  padding: 0;
  color: #323233;
  line-height: inherit;
  text-align: left;
  background-color: transparent;
  border: 0;
  resize: none;
}
</style>
